package main

import (
	"crypto/md5"
	"encoding/hex"
	"flag"
	"fmt"
	"time"
)

func main() {
	var site = flag.String("site", "", "site name in web.toml")
	flag.Parse()
	var name1, pwd1 string
	fmt.Println("Input administrator UserName and Password (name pwd):")
	fmt.Scanf("%s %s\n", &name1, &pwd1)

	conf1 := readToml("web.toml")
	cfg, ok := conf1.Sites[*site]
	if !ok {
		panic("must run with '-site sitename' flag")
	}
	db1 := NewMyDB(cfg["Addr"], cfg["User"], cfg["Password"], cfg["Database"])
	AddUser(db1, 0, name1, "administor", HexMd5(pwd1), "127.0.0.1")
	db1.Close()
}

const adduser_sql = `insert into users(gid,uname,showname,pwd_md5,from_ip,reg_tm,login_tm) 
	values(?,?,?,?,?,?,NULL)`

func AddUser(mydb *MyDB, gid int, name, shown, pwd, ip string) error {
	db1 := mydb.Conn
	_, err := db1.Exec(adduser_sql, gid, name, shown, pwd, ip, time.Now())
	if err != nil {
		panic(err)
	}
	return err
}

func HexMd5(s string) string {
	enc1 := md5.Sum([]byte(s))
	return hex.EncodeToString(enc1[:])
}
